package com.sdk.springbootadvancedsearch.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sdk.springbootadvancedsearch.domain.request.SortCondition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SortBuilder {

    public <T> void buildSorts(QueryWrapper<T> wrapper, List<SortCondition> sortConditions) {
        if (sortConditions == null || sortConditions.isEmpty()) {
            //  默认按创建时间倒序排序
            wrapper.orderByDesc("created_time");
            return;
        }

        // 1. 按优先级排序 (sort值越小优先级越高)
        List<SortCondition> sortedConditions = sortConditions.stream()
                .sorted(Comparator.comparingInt(SortCondition::getSort))
                .collect(Collectors.toList());

        // 2. 应用排序条件
        for (SortCondition sort : sortedConditions) {
            try {
                validateSort(sort);

                String column = StringUtils.camelToUnderline(sort.getKey());

                if ("desc".equalsIgnoreCase(sort.getOrderBy())) {
                    wrapper.orderByDesc(column);
                } else {
                    wrapper.orderByAsc(column);
                }
            } catch (Exception e) {
                log.error("构建排序条件失败: sort={}, error={}", sort, e.getMessage());
                throw new IllegalArgumentException("排序条件构建失败: " + sort.getKey(), e);
            }
        }
    }

    private void validateSort(SortCondition sort) {

        // 检查排序方向
        if (!"asc".equalsIgnoreCase(sort.getOrderBy()) &&
                !"desc".equalsIgnoreCase(sort.getOrderBy())) {
            throw new IllegalArgumentException("无效的排序方向: " + sort.getOrderBy());
        }
    }
}
